/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package jaspell;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.List;
import java.util.StringTokenizer;

/**
 *
 * @author alejandro
 */
public class JaspellDictionaryIO {

    public static Hashtable<String, Integer> loadDictionary(String path) throws IOException {
        Hashtable<String, Integer> dictionary = new Hashtable<String, Integer>();
        File file = new File(path);
        FileReader fileReader = new FileReader(file);
        BufferedReader bufferedReader = new BufferedReader(fileReader);
        String line, word, freq;
        StringTokenizer tokenizer;
        while ((line = bufferedReader.readLine()) != null) {
            tokenizer = new StringTokenizer(line, ":");
            word = tokenizer.nextToken();
            freq = tokenizer.nextToken();
            dictionary.put(word.trim(), Integer.valueOf(freq.trim()));
        }
        bufferedReader.close();
        return dictionary;
    }

    public static void merge(String path1, String path2, String outPath) throws IOException {
        Hashtable<String, Integer> dict1 = loadDictionary(path1);
        Hashtable<String, Integer> dict2 = loadDictionary(path2);
        String word;
        for (Enumeration<String> wordsIn2 = dict2.keys(); wordsIn2.hasMoreElements();) {
            word = wordsIn2.nextElement();
            if (dict1.containsKey(word)) {
                dict1.put(word, dict1.get(word) + dict2.get(word));
            } else {
                dict1.put(word, dict2.get(word));
            }
        }
        File file = new File(outPath);
        FileWriter fileWriter = new FileWriter(file);
        BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
        List<String> sortedWords = new ArrayList<String>();
        for (Enumeration<String> wordsIn1 = dict1.keys(); wordsIn1.hasMoreElements();) {
            sortedWords.add(wordsIn1.nextElement());
        }
        Collections.sort(sortedWords);
        for (String sword : sortedWords) {
            bufferedWriter.write(sword + " : " + dict1.get(sword) + "\n");
        }

        bufferedWriter.flush();
        bufferedWriter.close();
    }

    public static void main(String[] args) throws IOException {
        String dic1 = "/home/alejandro/projects/lariverosc/data/Jaspell/dict/spanish.txt";
        String dic2 = "/home/alejandro/projects/lariverosc/data/Jaspell/dict/SnomedES-WordList.txt";
        String out = "/home/alejandro/projects/lariverosc/data/Jaspell/dict/spanish+snomed.txt";
        merge(dic1, dic2, out);

    }
}
